import Taro from '@tarojs/taro'
import React, { useState, useEffect } from 'react'
import { View } from '@tarojs/components'
import dayjs,{ weeks } from '@src/utils/dateTimeUtil'
import './index.scss'

const dayLabel = ['前天','昨天','今天','明天','后天']

function getDayLabel(day, distince) {
  if(distince >= -2 && distince <=2){
    return dayLabel[distince + 2]
  }else{
    return weeks[day]
  }
}

/**
 * 日期选择
 * @param {*} config 属性配置
 * @example {
 *  value: null,                //当前选择的日期
 *  before: 0                   //可向前选择的天数
 *  after: 6                    //可向后选择的天数
 *  onChange: onChange(value)   //选择改变事件
 * }
 */
function DateTabs ({value, before = 0, after=6, onChange, className=''}) {
  const [date, setDate] = useState(value)

  function hanleOnChange (value) {
    setDate(value)
    if(onChange){
      onChange(value)
    }
  }
  
  function renderList(before, after) {
    const items = []
    let today = dayjs()
    let selected
    for(let i=-before; i <= after; i++){
      let dateItem = i < 0 ? today.subtract(-i,'day') : i == 0 ? today : today.add(i, 'day')
      selected = !date && i == 0 ? true : dateItem.isSame(date,'day') 
      items.push(<View className={`dateItem${selected ? ' selected' : ''}`} key={i} onClick={() => hanleOnChange(dateItem)}>
        <View className='label'>{getDayLabel(dateItem.day(), i)}</View>
        <View className='value'>{dateItem.format('MM-DD')}</View>
      </View>
      )
    }
    return items
  }

  return <View className={`datePicker ${className}`}>
    {
      renderList(before, after)
    }
  </View>
}

export default DateTabs
